<template>
  <div v-if="modal1VisibleDz">
    <div class="mask"></div>
    <div class="popup-frame">
      <div class="left">
        <div class="left-image">
          <template v-if="form.imageList[fileListActive]">
            <a-image style="width: 100%; height: 100%;" :src="form.imageList[fileListActive].compressImage" :preview="{
              src: form.imageList[fileListActive].imgPath,
            }" />
          </template>
          <template v-else></template>
        </div>
        <div class="left-title">
          <a-input placeholder="为作品添加标题" v-model:value="form.picTitle" @change="inputChange('picTitle')" />
        </div>
        <div class="left-content ">
          <div class="label-box">
            <TagSelector :all-tags="tags" v-model:selected-ids="form.tagIds" @change="changeTag"/>
          </div>
        </div>

        <div class="left-content">
          <a-textarea v-model:value="form.picContent" placeholder="为作品添加描述" :auto-size="false" @change="inputChange('picContent')"
            style="height: 100%; resize: none;" class="custom-input" />
        </div>
      </div>
      <div class="right">
        <div class="right-title">
          上传素材
          <div class="popup-x-x" @click="closePopup">
            <CloseOutlined />
          </div>
        </div>
        <div class="right-select">
          <a-row :gutter="20">
            <a-col :span="24">
              <a-cascader v-model:value="form.columnId" :options="columnsList" style="width: 100%"
                max-tag-count="responsive" placeholder="请选择栏目" @change="handleChange" />
            </a-col>
          </a-row>
        </div>
        <div class="file-list-frame">
          <div class="file-item" v-for="(item, index) in form.imageList" :key="item" @click="selectLook(index)"
            draggable="true" @dragstart="onDragStart(item, index)" @drop="onDrop(item, index)" @dragover.prevent
            @dragenter="onDragenter(item, index)" @dragleave="onDragleave($event, item, index)" :style="{
              'border': dragActiveIndex === index ? `2px solid #a11f24` : '2px solid #fff'
            }">
            <img :src="item.compressImage" alt="" />
            <div class="file-item-x-x" @click="deleteFile(index)">
              <CloseOutlined />
            </div>
          </div>
          <div class="file-item" v-for="(item, index) in 30 - form.imageList.length">

          </div>
        </div>
        <div class="file-upload">
          <upload @change="getFiles"></upload>
        </div>
        <div class="file-upload">
          <uploadFile
            :file="form.fileId"
            :maxCount="10"
            listType="text"
            accept="*"
            @loading="setLoading"
            @change="getFileCopy($event, 'fileId')"
          />
        </div>
        <div class="file-button">
          <div>
          </div>
          <div>
            <a-button type="primary" info style="margin-right: 16px;" @click="closePopup">取消</a-button>
            <a-button type="primary" danger :loading="loading" @click="onSubmit">上传</a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineExpose, defineEmits } from 'vue'

import { CloseOutlined } from '@ant-design/icons-vue'
import upload from './components/upload.vue'
import uploadFile from './components/uploadFile.vue'
import TagSelector from './components/TagSelector.vue';
import { useHttp } from '@/api/http'
import methods from '@/utils/methods'
import { message } from 'ant-design-vue'
const emit = defineEmits(['ok', 'openEdit', 'delOk'])

const modal1VisibleDz = ref(false)
const loading = ref(false)

const form = ref({
  keyWord: '', // 关键字
  picTitle: '', //	内容标题		false
  imageList: [], //	内容组		false
  columnId: [], // 栏目id
  materialId: null, // 分类id
  tagId: [], // 标签
  tagIds: [], // 标签回显
  tagJson: [], // 标签
  picContent: '', //	内容内容		false
  video: [], // 视频链接
  fileId: '', // 附件
  id: '', // 主键
});



const verify = {
  picTitle: '请填写标题', //	内容标题		false
  columnId: '请选择栏目', // 栏目id
}
const videoLink = ref('')
const fileListActive = ref(0)

const closeScroll = () => {
  // 使用JavaScript添加禁用滚动的类
  document.documentElement.style.overflow = 'hidden';
  document.body.style.overflow = 'hidden';
}
const openScroll = () => {
  // 使用JavaScript添加禁用滚动的类
  document.documentElement.style.overflow = '';
  document.body.style.overflow = '';
}

const ondeLoad = ref(true)
// 打开
const open = () => {

  if(ondeLoad.value) {
    ondeLoad.value = false
    getColumnLists();
    getColumnsList();
    getCategories();
  }
  closeScroll()
  modal1VisibleDz.value = true
  reset()
}

// 关闭
const closePopup = () => {
  openScroll()
  modal1VisibleDz.value = false
}


const editIndex = ref(0)
const isEdit = ref(false)

const isFileLoading = ref(false);
// 文件是否上传中
const setLoading = (e) => {
  console.log(e)
  isFileLoading.value = e
}

// 编辑
const edit = (item, index) => {
  if(ondeLoad.value) {
    ondeLoad.value = false
    getColumnLists();
    getColumnsList();
    getCategories();
  }
  modal1VisibleDz.value = true
  editIndex.value = index
  form.value.id = item
  isEdit.value = true
  useHttp.get('/cms/pic/queryById', {
    id: item
  }).then(res => {
    for (let i in form.value) {
      form.value[i] = res.result[i];
    }
    if (form.value.tagJson) {
      form.value.tagJson = JSON.parse(form.value.tagJson);

    } else {
      form.value.tagJson = [];
    }
    form.value.columnId = methods.getSplitData(form.value.columnId) || [];
    form.value.video = methods.getSplitData(res.result.videoUrl) || [];
    form.value.tagId = methods.getSplitData(res.result.tagId) || [];
    form.value.tagIds = methods.getSplitData(res.result.tagId) || [];
    columnIdChange(form.value.columnId);
    inputChange('picTitle');
    materialIdChange(form.value.materialId);
    inputChange('fodderId');
  })
}

// 重置
const reset = () => {
  form.value = {
    keyWord: '', // 关键字
    picTitle: '', //	内容标题		false
    imageList: [], //	内容组		false
    columnId: [], // 栏目id
    materialId: null, // 分类id
    tagId: [], // 标签
    picContent: '', //	内容内容		false
    video: [], // 视频链接
    fileId: '', // 附件
    id: '', // 主键
  }
}
// 添加视频链接
const addVideoLink = () => {
  form.value.video.push(videoLink.value)
  videoLink.value = ''
}
// 删除视频链接
const delVideoUrl = (index) => {
  form.value.video.splice(index, 1)
}

const dragObj = {
  startIndex: -1,
  endIndex: -1,
}
const dragActiveIndex = ref(-1)
// 拖拽
function onDragStart(item, index) {
  // 开始拖拽
  dragObj.startIndex = index
}
function onDragenter(item, index) {
  // 拖拽入
  dragActiveIndex.value = index
}
function onDragleave(event, item, index) {
  // 拖拽出
  const relatedTarget = event.relatedTarget;
  // 如果 relatedTarget 存在并且是 container 的子元素，则不视为真正离开
  if (event.currentTarget.contains(relatedTarget)) {
    return;
  }
  dragActiveIndex.value = -1
}
function onDrop(item, index) {
  // 拖拽完成
  if (index === dragObj.startIndex) return
  dragObj.endIndex = index
  // 临时保存第一个元素
  let temp = methods.deepClone(form.value.imageList[dragObj.startIndex])
  // 将第二个元素赋值给第一个位置
  form.value.imageList[dragObj.startIndex] = form.value.imageList[dragObj.endIndex];
  // 将临时保存的第一个元素赋值给第二个位置
  form.value.imageList[dragObj.endIndex] = temp;
  dragActiveIndex.value = -1
}

// 获取上传文件
const getFiles = (e) => {
  const arr = []
  for (let i of e) {
    arr.push({
      imgAbridgeHeight: 0,
      imgAbridgePath: i.imgAbridgePath,
      imgAbridgeSize: 0,
      imgAbridgeWidth: 0,
      imgHeight: 0,
      imgPath: i.imageUrl,
      imgSize: 0,
      imgWidth: 0,
      compressImage: i.compressImage,
    })
  }
  form.value.imageList.push(...arr)
}
const getFileCopy = (e) => {
  let arr = []
  for(let i of e) {
    arr.push(i.imageUrl)
  }
  form.value.fileId = arr.join(',')
  columnNameData.value = false
}
// 删除文件
const deleteFile = (index) => {
  if (index === fileListActive.value) fileListActive.value = 0
  form.value.imageList.splice(index, 1)
}
// 选择查看
const selectLook = (index) => {
  fileListActive.value = index
}

// 删除素材
const delPic = () => {
  useHttp.delete('/cms/pic/delete', {
    id: form.value.id
  }).then(res => {
    message.success('删除成功！')
    modal1VisibleDz.value = false
    loading.value = false;
    let delData = {
      editIndex: editIndex.value,
    }
    emit('delOk', delData)
    reset()
  })
}

// 分类
const materialJson = ref([]);
// 获取分类
const getColumnLists = () => {
  useHttp.get('/cms/material/list', {
    pageSize: 100,
    pageNo: 1,
  }).then(res => {
    materialJson.value = res.result.records
  })
};

// 获取栏目
const columnsList = ref([])
const getColumnsList =  () => {
  useHttp.get('/cms/column/pcList', {
    pageSize: 100,
    pageNo: 1,
  }).then(res => {
    columnsList.value = methods.buildTree(res.result.records, 'columnName', 'id');
  })
}
const columnNameData = ref(true)
const handleChange = (value) => {
  columnNameData.value = true
  for (let i of columnsList.value) {
    if (i.id === value[0] && i.columnName === '图片资料') {
      columnNameData.value = false
      break;
    }
  }

};

// 获取标签
const tags = ref([])
// useHttp.get('/cms/tag/list', {
//   pageSize: 1000,
//   pageNo: 1,
// }).then(res => {
//   tags.value = res.result.records
// })

// 获取标签
const getCategories = () => {
  useHttp.get('/cms/categories/list',{
    pageSize: 100,
    pageNo: 1,
  }).then(async res => {
    let arr = []
    for (let i of res.result.records) {
      // const result = await getTags(i.id)
      arr.push({
        value: i.id,
        label: i.name,
        // children: result
      })
    }
    tags.value = arr
  })
}
const getTags = (id) => {
  return new Promise((resolve, reject) => {
    useHttp.get('/cms/tag/list', {
      pageNo: 1,
      pageSize: 100,
      categoryId: id
    }).then(res => {
      let arr = []
      for (let i of res.result.records) {
        arr.push({
          value: i.id,
          label: i.name,
        })
      }
      resolve(arr)
    })
  })
}

// 获取关键字
const keywords = ref({
  material: '',
  tag: '',
  picTitle: '',
  column: '',
  fodderId: '',
  picContent: '',
})
const changeKeyWords = (key, value) => {
  keywords.value[key] = value;
}
const inputChange = (key) => {
  changeKeyWords(key, form.value[key])
}
const columnIdChange = (e) => {
  let arr = []
  for (let i of columnsList.value) {
    for (let j of e) {
      if (j === i.id) {
        arr.push(i.columnName)
      }
    }
  }
  changeKeyWords('column', arr.join(','))
}
const materialIdChange = (e) => {
  for (let i of materialJson.value) {
    if (e === i.id) {
      changeKeyWords('material', i.sourceMaterialName)
      break;
    }
  }
}
const changeTag = (e) => {
  let arr = [];
  let arr2 = [];
  for (let i of e) {
    arr.push(i.name)
    arr2.push(i.id)
  }
  form.value.tagId = arr2
  changeKeyWords('tag', arr.join(','))

}

function getTagsList(id) {
  let arr = []
  for (let i of tags.value) {
    if (i.value === id) {
      for (let j of i.children) {
        arr.push(j.value)
      }
      return arr
    }
  }
}
// 子组件删除
const handleChildRemove = (item) => {

  columnNameData.value = item;
  form.value.fileId = ''



}

//  提交
const onSubmit = async () => {
  if(isFileLoading.value) {
    message.error('文件上传中')
    return
  }
  const data = methods.deepClone(form.value);

  // console.log(data, "提交得时候");

  if (form.value.imageList.length === 0) {
    message.error('请上传图片')
    return
  }


  data.keyWord = ''
  console.log(keywords.value)
  for (let i in keywords.value) {
    if (keywords.value[i]) {
      data.keyWord += keywords.value[i]
    }
  }

  // let tagJsonArr = []
  // if (data.tagJson) {
  //   for (let i of data.tagJson) {
  //     if (i.length === 1) {
  //       let arrData = getTagsList(i[0])

  //       tagJsonArr.push(...arrData)
  //     } else {
  //       tagJsonArr.push(i[1])
  //     }
  //   }
  // }

  data.tagJson = JSON.stringify(data.tagId)
  data.tagId = data.tagId.join(',')
  data.columnId = data.columnId.join(',');
  data.videoUrl = data.video.join(',');

  for (let i in verify) {
    if (!data[i]) {
      message.error(verify[i])
      return
    }
  }
  if (columnNameData.value && !data.fileId) {
    message.error('请上传附件')
    return
  }

  loading.value = true;
  if (data.id) {
    useHttp.post('/cms/pic/edit', data).then(res => {
      message.success('编辑成功！')
      modal1VisibleDz.value = false
      loading.value = false;
      let editData = {
        picTitle: data.picTitle,
        editIndex: editIndex.value,
        imageList: data.imageList
      }
      emit('editOk', editData)
      emit('ok')
      reset()
    }).catch(err => {
      loading.value = false;
    })
  } else {
    useHttp.post('/cms/pic/add', data).then(res => {
      message.success('上传成功！')
      modal1VisibleDz.value = false
      loading.value = false;
      emit('ok')
      reset()
    }).catch(err => {
      loading.value = false;
    })
  }
}


defineExpose({
  open,
  edit
})


</script>

<style scoped>
.mask {
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1001;
}

.popup-frame {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 107.6666666695vh;
  height: 85vh;
  background-color: var(--color-bg-20);
  border-radius: 24px;
  display: flex;
  justify-content: space-between;
  overflow: hidden;
  z-index: 1001;



  .left {
    width: calc(312px);
    height: calc(100% - 48px);
    background-color: var(--color-bg-20);
    padding: 24px;
    display: flex;
    gap: 10px;
    flex-direction: column;
    justify-content: space-between;

    .left-image {
      width: 100%;
      overflow: hidden;
      background-color: var(--bg-color-eee);
      border-radius: 12px;
      height: calc(33.333% - 10px);
      display: flex;
      justify-content: center;
      align-items: center;
      color: #333;
      border: 0.5px solid var(--border-color-d9);

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 12px;
      }
    }

    .custom-input {
      height: 40px;
      font-size: 16px;
    }


    .left-content {
      width: 100%;
      border-radius: 12px;
      height: calc(33.333% - 10px - 30px);
    }

    .label-box {
      width: 100%;
      height: 100%;
      border-radius: 12px;
      border: 0.5px solid var(--border-color-d9);


    }

    .left-tag {
      width: 100%;
      border-radius: 12px;
      height: calc(33.333% - 10px - 30px);
      border: 1px solid #d9d9d9;
      background-color: #fff;
      padding: 10px;

      .video-link-frame {
        height: calc(100% - 42px);
        overflow-y: auto;
        margin-top: 5px;
        font-size: 16px !important;
        line-height: 18px !important;

        .video-link-item {
          height: 24px;
          text-decoration: underline;
          color: #3261af;
          position: relative;
          width: calc(100% - 20px);

          .item-text {
            height: 24px;
            line-height: 24px;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .video-link-item-x-x {
            position: absolute;
            left: 100%;
            top: 0;
            height: 100%;
            width: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: red;

            span {
              cursor: pointer;
            }
          }
        }

        .video-link-item:hover {
          background-color: #eee;
        }
      }
    }
  }

  .right {
    height: 100%;
    width: calc(100% - 312px);
    padding: 0 24px 24px 24px;
    display: flex;
    /* gap: 1vw; */
    /* justify-content:space-around; */

    flex-direction: column;

    .right-title {
      width: 100%;
      height: 70px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 20px;
      position: relative;
      color: var(--color-text);

      .popup-x-x {
        position: absolute;
        right: 24px;
        top: 50%;
        transform: translateY(-50%);

        span {
          cursor: pointer;
        }
      }
    }

    .right-select {
      height: 34px;
      align-items: center;
      margin-top: 20px;



    }



    .file-list-frame {
      height: calc(100% - 380px);
      width: calc(100%);
      display: grid;
      gap: 10px;
      grid-template-columns: repeat(4, 1fr);
      overflow-x: hidden;
      overflow-y: auto;
      margin: 40px 0px;

      .file-item {
        aspect-ratio: 1 / 1;
        border-radius: 12px;
        border: 1px dashed #bbb;
        cursor: pointer;
        position: relative;

        img {
          display: block;
          border-radius: 12px;
          object-fit: cover;
          width: 100%;
          height: 100%;
        }

        .file-item-x-x {
          position: absolute;
          right: 4px;
          top: 4px;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          border: 2px solid #fff;
          font-size: 18px;
          color: #fff;
          display: flex;
          font-size: 14px;
          justify-content: center;
          align-items: center;
          transition: all .3s;
          background-color: rgba(0, 0, 0, 0.5);

          span {
            cursor: pointer;
          }
        }
      }
    }

    .file-upload {
      margin: 20px 0px;
    }

    .file-button {
      margin: 30px 0px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .del-link {
        color: red;
        font-size: 13px;
        cursor: pointer;
      }
    }
  }
}
</style>
